import requests
from loguru import logger
from requests import ConnectTimeout
from typing import Union
from lib.request_tool.Filed import UrlsFiled


class UrlRequestBase:
    url = None
    response = None

    def get(self, **kwargs):
        self.response = requests.get(self.url, **kwargs, timeout=(10, 60))
        return self

    def post(self, **kwargs):
        self.response = requests.post(self.url, **kwargs, timeout=(10, 60))

        return self

    def put(self, **kwargs):
        self.response = requests.put(self.url, **kwargs, timeout=(10, 60))
        return self

    def delete(self, **kwargs):
        self.response = requests.delete(self.url, **kwargs, timeout=(10, 60))
        return self

    def get_json(self):
        return self.response.json()

    def get_response(self):
        return self.response


def request_url(url_obj: UrlsFiled, format='', **kwargs) -> Union[requests.Response, dict, str, bytes]:
    """
        请求路由中转函数
        Args:
            url_obj: UrlsFiled对象
            format: 返回格式 json content  text
        Kwargs:
            params:[可选]查询字符串（dict）
            data: [可选]请求体（dict）
            json: [可选]请求体（json）
            headers: [可选]请求头（dict）
            cookies: [可选]Cookie（dict or Dictionary）
            timeout: [可选]超时时间（float or tuple）
        Return:
          <Response [200]>
    """
    format_list = ['json', 'content', 'text']

    request = UrlRequestBase()
    request.url = url_obj.get_urls()
    method = url_obj.get_method()
    kwargs["headers"] = kwargs.get("headers", None) or url_obj.get_headers()

    logger.info("[Request] 请求地址: %s" % request.url)
    logger.info("[Request] 请求Method: %s" % method)

    if hasattr(request, method.lower()):
        try:
            res = getattr(request, method.lower())(**kwargs)
        except ConnectTimeout as e:
            logger.info("[Request] 请求超时: %s" % e)
            raise RuntimeError
            # raise OtherErr(ErrCode.request_timeout)
        if format_list[0] == format:
            return res.get_json()
        elif format_list[1] == format:
            return res.response.content
        elif format_list[2] == format:
            return res.response.text
        else:
            return res.response
    raise Exception('method not found')
